<?php
namespace Admin\Controller;
use Think\Controller;
class AdminController extends Controller {
	/* 空操作，用于输出404页面 */
	public function _empty() {
		$this->display ( "Public/404" );
	}
	/**
	 * 后台控制器初始化
	 */
	public function _initialize() {
		// 获取当前用户ID
		define('UID',is_login());
		if( !UID ){
			// 还没登录 跳转到登录页面
			$this->redirect('Public/login');
		}   
		//获取当前位置
		//获取账号信息
		$linkurl = IS_GET ? CONTROLLER_NAME.'/'.ACTION_NAME : '';
        $action = ACTION_NAME;
        $where = [
            'linkurl'   =>  $linkurl,
        ];
        $menu_name = D('Data')->get_row_data('Menu',$where);
        $member = D('Member')->get_member(UID);
        $parent = M('menu')->where(['linkurl'=>$linkurl])->getfield('pid');
		//获取菜单
		$menu = $this->getMenus();
		$user = M('Member')->find(UID);
		$this->assign('menu',$menu);
		$this->assign('menus',$menu);
		$this->assign('action',$action);
		$this->assign('menu_name',$menu_name);
		$this->assign('member',$member);
		$this->assign('admin',$user);
		$this->assign('parent',$parent);
	}
	//获取菜单
    final public function getMenus(){
        if(empty($menus)){
            $menus = array();
            // 获取主菜单
            $where['pid']   =   0;
            $where['hide']  =   0;
            $menus  =   M('Menu')->where($where)->select();
            foreach($menus as $key=>$val){
                // 判断主菜单权限
                if (!$this->checkRule(intval($val['id'])) ) {
                    unset($menus[$key]);
                    continue;//继续循环
                }
                $map['pid'] =   $val['id'];
                $map['hide']    =   0;
                $child = M('Menu')->where($map)->select();
                foreach ($child as $k=>$v){
                    // 判断子菜单权限
                    if (!$this->checkRule(intval($v['id']))) {
                        unset($child[$k]);
                        continue;//继续循环
                    }
                }
                $menus[$key]['child'] =  $child;
            }
        }
        return $menus;
    }
	//检测权限
	public function checkRule($id){
		if(UID == 1){return true;} //管理员允许访问任何页面
		//获取当前用户的权限规则
		$user = M('Member')->find(UID);
		$group = M('Group')->find($user['group_id']);
		$rules = $group['rules'];
		if(empty($rules)){
			return false;  //没有规则则没有任何权限
		}
		//如果是一个以上的权限规则就得拆分为数组
		if(strpos($rules,',') !== false){
			$arr = explode(',',$rules);
            //dump($arr);exit();
			if(in_array($id,$arr)){
				return true; //用户规则存在则返回真
			}else{
				return false;
			}
		}else{
			//说明规则只有一个
			if($id == $rules){
				return true;
			}else{
				return false;
			}
		}
	}
}
